package com.authentication.manager;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider;

/**
 * 委派 {@link JwtAuthenticationProvider}解析 bearer token 令牌
 * 是对 {@link ProviderManager} 的简单实现
 */
public class BearerTokenAuthenticationManager implements AuthenticationManager {

    private final AuthenticationProvider authenticationProvider;

    public BearerTokenAuthenticationManager(AuthenticationProvider authenticationProvider) {
        this.authenticationProvider = authenticationProvider;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        if (authenticationProvider.supports(authentication.getClass())) {
//            BearerTokenAuthenticationToken
            Authentication authenticate = authenticationProvider.authenticate(authentication);

            return authenticate;
        }

        return null;
    }
}
